#!/usr/bin/env bash

if [ -f ./variables.sh ]; then
  source ./variables.sh
elif [ -f scripts/variables.sh ]; then
  source scripts/variables.sh
else
  echo_r "Cannot find the variables.sh files, pls check"
  exit 1
fi

echo_r() {
  [ $# -ne 1 ] && return 0
  echo -e "\033[31m$1\033[0m"
}
echo_g() {
  [ $# -ne 1 ] && return 0
  echo -e "\033[32m$1\033[0m"
}
echo_y() {
  [ $# -ne 1 ] && return 0
  echo -e "\033[33m$1\033[0m"
}
echo_b() {
  [ $# -ne 1 ] && return 0
  echo -e "\033[34m$1\033[0m"
}


setOrdererEnvs() {
  export CORE_PEER_LOCALMSPID=${ORDEREDMSP}
  export CORE_PEER_ADDRESS=${ORDERER0_URL}
  export CORE_PEER_MSPCONFIGPATH=${ORDERER0_ADMIN_MSP}
  export CORE_PEER_TLS_ROOTCERT_FILE=${ORDERER0_TLS_ROOTCERT}
}

setEnvs() {
  local org=$1
  local peer=$2

  local t=""
  export CORE_PEER_LOCALMSPID="Org${org}MSP"
  t="\${ORG${org}_PEER${peer}_URL}" && export CORE_PEER_ADDRESS=$(eval echo $t)
  t="\${ORG${org}_ADMIN_MSP}" && export CORE_PEER_MSPCONFIGPATH=$(eval echo $t)
  t="\${ORG${org}_PEER${peer}_TLS_ROOTCERT}" && export CORE_PEER_TLS_ROOTCERT_FILE=$(eval echo $t)
  # export FABRIC_LOGGING_SPEC="INFO"
}

fetchBlock() {
  local channel=$1
  local orderer_url=$2
  local orderer_tls_rootcert=$3
  local num=$4
  local block_file=$5

  setOrdererEnvs
  peer channel fetch $num ${block_file} \
    -o ${orderer_url} \
    -c ${channel} \
    --tls \
    --cafile ${orderer_tls_rootcert} \
    >&log.txt

  if [ $? -ne 0 ]; then
    cat log.txt
    echo_r "Fetch block $num of channel $channel failed"
    return 1
  else
    echo "=== Fetch block $num of channel $channel OK === "
    return 0
  fi
}

signconfigtx(){
  local channel=$1
  local org=$2
  local peer=$3
  local tx=$4
  setEnvs $org $peer
  peer channel signconfigtx -f ${tx} >&log.txt
  rc=$?
  [ $rc -ne 0 ] && cat log.txt
  if [ $rc -ne 0 ]; then
    echo_r "Sign channel config tx for channel $channel by org $org/peer $peer failed"
  fi
}

channelUpdate() {
  local channel=$1
  local org=$2
  local peer=$3
  local orderer_url=$4
  local orderer_tls_rootcert=$5
  local tx=$6

  setEnvs $org $peer

  peer channel update \
    -c ${channel} \
    -o ${orderer_url} \
    -f ${tx} \
    --tls \
    --cafile ${orderer_tls_rootcert}
}



